package yu.liu.personal.app.myapplication.ui.main;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import yu.liu.personal.app.myapplication.R;
import yu.liu.personal.app.myapplication.components.views.UntouchableViewPager;
import yu.liu.personal.app.myapplication.ui.BaseUI;
import yu.liu.personal.app.myapplication.ui.fragment.AVGListFragment;
import yu.liu.personal.app.myapplication.ui.fragment.BaseFragment;
import yu.liu.personal.app.myapplication.utils.Tools;

/**
 * Created by Administrator on 2016/9/24.
 */

public class MainPage extends BaseUI {

    @BindView(R.id.ivTitleMain) ImageView ivTitleMain;
    @BindView(R.id.tvTitleMain) TextView tvTitleMain;
    @BindView(R.id.boxNavigatorMain) LinearLayout boxNavigatorMain;
    @BindView(R.id.vpContentMain) UntouchableViewPager vpContentMain;
    private FragmentStatePagerAdapter adapterContentMain;

    private List<TextView> titles;
    private List<BaseFragment> fragments;
    private int screenHeight;
    private int originHeight;
    private boolean titleCollapse;
    private float startY;
    private int limit;
    private int direction;
    private boolean moved;
    boolean scrollDown;
    private AnimatorSet aSet;

    private final String[] constTitles = {"机娘数据"};

    private AVGListFragment avgListFragment;

    @Override
    protected View loadViews() {
        contentView = LayoutInflater.from(resContext)
                .inflate(resManager.getResourceID("layout", "layout_main_page"), null);
        ButterKnife.bind(this, contentView);
        return contentView;
    }

    @Override
    protected void loadMembers() {
        titleCollapse = false;
        limit = Tools.dpToPx(resContext, 120);
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = getWindowManager();
        wm.getDefaultDisplay().getMetrics(dm);
        screenHeight = dm.heightPixels;
        originHeight = screenHeight - Tools.dpToPx(resContext, 200);
        ViewGroup.LayoutParams cparams = contentView.getLayoutParams();
        cparams.height = screenHeight + Tools.dpToPx(resContext, 100);
        contentView.setLayoutParams(cparams);
        if (titles == null) {
            titles = new ArrayList<>();
            for (int i = 0; i < constTitles.length; i++) {
                TextView tv = new TextView(resContext);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
                        ViewGroup.LayoutParams.MATCH_PARENT, 1);
                tv.setLayoutParams(params);
                tv.setTag(i);
                tv.setOnClickListener(new NavigatorClickListener());
                tv.setText(constTitles[i]);
                tv.setTextSize(20);
                tv.setGravity(Gravity.CENTER);
                tv.setTextColor(Color.parseColor("#333333"));
                boxNavigatorMain.addView(tv);
                titles.add(tv);
            }
        }
        if (fragments == null) {
            fragments = new ArrayList<>();
            avgListFragment = new AVGListFragment();
            fragments.add(avgListFragment);
        }
        adapterContentMain = new ContentAdapter(getSupportFragmentManager());
        vpContentMain.setAdapter(adapterContentMain);
    }

    @Override
    protected void postSetup() {
        adapterContentMain.notifyDataSetChanged();
        ivTitleMain
                .setImageResource(resManager.getResourceID("mipmap", "pic_title_bg_0"));
        vpContentMain.setCurrentItem(0);
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        super.dispatchTouchEvent(ev);
        return onTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        moved = true;
        boolean result = false;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // init all params
                startY = event.getRawY();
                direction = 0;
                scrollDown = false;
                break;
            case MotionEvent.ACTION_MOVE:
                // translate the title
                // change the alpha vale of mask
                float delta = event.getRawY() - startY;
                if (delta > 5) {
                    // scroll down
                    if (titleCollapse && avgListFragment != null &&
                        avgListFragment.getListIsTop()) {
                        if (delta < limit) {
                            contentView.setTranslationY(delta - limit);
                            ivTitleMain.setAlpha((delta / limit));
                            tvTitleMain.setAlpha(1f - (delta / limit));
                            result = true;
                            scrollDown = true;
                        } else {
                            contentView.setTranslationY(0f);
                            ivTitleMain.setAlpha(1f);
                            tvTitleMain.setAlpha(0f);
                        }
                    }
                    direction = 1;
                } else if(delta < -5) {
                    // scroll up
                    if (!titleCollapse) {
                        if (Math.abs(delta) < limit) {
                            contentView.setTranslationY(delta);
                            ivTitleMain.setAlpha(1f + (delta / limit));
                            tvTitleMain.setAlpha(Math.abs(delta) / limit);
                            result = true;
                        } else {
                            contentView.setTranslationY(-limit);
                            ivTitleMain.setAlpha(0f);
                            tvTitleMain.setAlpha(1f);
                        }
                    }
                    direction = 2;
                } else {
                    moved = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                // finish the animation
                // reset all params
                if(moved) {
                    aSet = new AnimatorSet();
                    if (direction == 1) { // down
                        if (titleCollapse && scrollDown &&
                            contentView.getTranslationY() <= 0f) {
                            ObjectAnimator a1 = ObjectAnimator.ofFloat(contentView,
                                    "translationY", contentView.getTranslationY(), 0f);
                            a1.setDuration(200);
                            ObjectAnimator a2 = ObjectAnimator.ofFloat(ivTitleMain,
                                    "alpha", ivTitleMain.getAlpha(), 1f);
                            a2.setDuration(200);
                            ObjectAnimator a3 = ObjectAnimator.ofFloat(tvTitleMain,
                                    "alpha", tvTitleMain.getAlpha(), 0f);
                            aSet.playTogether(a1, a2, a3);
                            aSet.start();
                            titleCollapse = false;
                            result = true;
                        }
                    } else if(direction == 2) { // up
                        if (!titleCollapse && contentView.getTranslationY() <= 0f) {
                            ObjectAnimator a1 = ObjectAnimator.ofFloat(contentView,
                                    "translationY", contentView.getTranslationY(),
                                    -limit);
                            a1.setDuration(200);
                            ObjectAnimator a2 = ObjectAnimator.ofFloat(ivTitleMain,
                                    "alpha", ivTitleMain.getAlpha(), 0f);
                            a2.setDuration(200);
                            ObjectAnimator a3 = ObjectAnimator.ofFloat(tvTitleMain,
                                    "alpha", tvTitleMain.getAlpha(), 1f);
                            aSet.playTogether(a1, a2, a3);
                            aSet.start();
                            titleCollapse = true;
                            result = true;
                        }
                    }
                }
                break;
            default:
                break;
        }
        return result;
    }

    private class ContentAdapter extends FragmentStatePagerAdapter {

        public ContentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments == null ? 0 : fragments.size();
        }
    }

    private class NavigatorClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int index = (Integer) v.getTag();
            vpContentMain.setCurrentItem(index);
        }
    }
}
